<template>
  <el-tabs type="border-card">
    <el-tab-pane label="影楼基本信息">
      <el-form
        ref="form"
        label-width="180px"
        :model="studioForm.formData"
        :rules="studioForm.rules"
        style="overflow-x: auto"
      >
        <el-form-item
          label="影楼名"
          prop="name"
        >
          <el-input
            style="width: 220px"
            placeholder="影楼名"
            v-model.trim="studioForm.formData.name"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item
          label="账号"
          prop="account"
        >
          <span v-if="id > 0">{{ studioForm.formData.account }}</span>
          <el-input
            v-else
            style="width: 220px"
            v-model.trim="studioForm.formData.account"
            placeholder="请输入账号"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input
            style="width: 220px"
            placeholder="手机号"
            v-model.trim="studioForm.formData.mobile"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="!id"
          label="初始密码"
        > 12345 </el-form-item>

        <el-form-item
          label="影楼电话"
          prop="tel"
        >
          <el-input
            style="width: 220px"
            placeholder="影楼电话"
            v-model.trim="studioForm.formData.tel"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item
          label="影楼地址"
          prop="address"
        >
          <el-input
            style="width: 350px"
            placeholder="影楼地址"
            v-model.trim="studioForm.formData.address"
            maxlength="150"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item
          label="等级"
          prop="level"
        >
          <el-select
            v-model="studioForm.formData.level"
            placeholder="请选择"
            filterable
            clearable
            :loading="selectLoading"
            @focus="getLevelSelect"
          >
            <el-option
              v-for="item in levels"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select>
          <div class="tips">不选则为默认等级</div>
        </el-form-item>

        <el-form-item
          label="等级结束时间"
          prop="levelEndTime"
        >
          <el-date-picker
            v-model="studioForm.formData.levelEndTime"
            align="right"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
          <div class="tips">达到结束时间后，该影楼等级会默认变成普通</div>
        </el-form-item>

        <el-form-item
          label="是否启用"
          prop="enable"
        >
          <el-select
            v-model="studioForm.formData.enable"
            value-key="name"
            placeholder="状态"
          >
            <el-option
              v-for="(item, key) in $CONST.ACTIVE_STATUS"
              :key="key"
              :label="item.title"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            style="margin-right: 100px"
            @click="gotoList"
            v-waves
          >返回</el-button>
          <el-button
            type="primary"
            :loading="studioForm.loading"
            @click="onSubmit"
            v-waves
          >{{ this.studioForm.loading ? "提交中" : "保存" }}</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane
      :disabled="!isEditMode"
      label="余额充值"
    >
      <el-form
        ref="balanceForm"
        label-width="180px"
        :model="balanceForm"
        :rules="balanceFormRules"
        style="overflow-x: auto"
      >
        <el-form-item label="当前余额">
          ¥ {{ studioForm.formData.offLineAmount }}
        </el-form-item>
        <el-form-item label="当前工厂币">
          {{ studioForm.formData.amount }} 个
        </el-form-item>
        <el-form-item
          label="操作类型"
          prop="isPlus"
        >
          <el-select
            v-model="balanceForm.isPlus"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, key) in plusMinus"
              :key="key"
              :label="item.title"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="金额"
          prop="amount"
        >
          <el-input-number
            style="width: 180px"
            :min="1"
            :max="999999.99"
            :precision="2"
            :step="1"
            v-model="balanceForm.amount"
          ></el-input-number>
        </el-form-item>

        <el-form-item
          label="备注"
          prop="remark"
        >
          <el-input
            style="width: 200px"
            type="textarea"
            v-model="balanceForm.remark"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="confirmPassword"
        >
          <el-input
            style="width: 200px"
            type="password"
            v-model="balanceForm.confirmPassword"
            auto-complete="off"
            :disabled="factory && !factory.confirmPassword"
          ></el-input>
          <router-link style="margin-left:20px;"
          class="inlineBlock"
          :to="{ name: '工厂信息' }" v-if="factory && !factory.confirmPassword">
            <el-link type="primary">设置确认密码</el-link>
          </router-link>
        </el-form-item>
        <el-form-item>
          <el-button @click="$refs.balanceForm.resetFields()">重置</el-button>
          <el-button
            :disabled="factory && !factory.confirmPassword"
            type="primary"
            :loading="formLoading"
            @click="onReCharge"
            v-waves
          >{{ this.formLoading ? "提交中" : "保存" }}</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>

    <el-tab-pane
      :disabled="!isEditMode"
      label="余额充值记录"
    >
      <list-condition-template
        ref="table"
        :rows="rows"
        :defaultSort="{ prop: 'createTime', order: 'descending' }"
        :total="total"
        @page-info-change="handlePageInfoChange"
        :search-data="listQuery"
        :batch-column="false"
      >
        <template slot="condition">
          <el-form-item prop="keyword">
            <el-input
              placeholder="关键词"
              v-model="listQuery.keyword"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item prop="dateArray">
            <el-date-picker
              v-model="listQuery.dateArray"
              type="daterange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="center"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </template>
        <template slot="columns">
          <el-table-column
            label="订单金额（元）"
            align="center"
            property="amount"
          ></el-table-column>
          <el-table-column
            label="备注"
            min-width="150"
            align="center"
            property="remark"
          ></el-table-column>
          <el-table-column
            label="充值状态"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.finish ? "完成" : "未完成" }}
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            property="createTime"
          ></el-table-column>
        </template>
      </list-condition-template>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import studioUserApi from '@/api/photoStudioUser'
import studioAPI from '@/api/photoStudio'
import factoryApi from '@/api/factory'
import levelAPI from '@/api/level'
import amountChangeLogAPI from '@/api/amountChangeLog'
import ListConditionTemplate from '@/components/templates/listConditionTemplate'
import { mapGetters } from 'vuex'
export default {
  props: ['id'],
  name: 'info',
  components: {
    ListConditionTemplate
  },
  data () {
    return {
      factory: null,
      listQuery: {
        keyword: null,
        dateArray: null,
        photoStudioId: this.id,
        type: this.$CONST.AMOUNT_CHANGE_TYPE.RECHARGE.name
      },
      formLoading: false,
      plusMinus: [
        { title: '增加', value: true },
        { title: '减少', value: false }
      ],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now()
        },
        shortcuts: [
          {
            text: '一周后',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          },
          {
            text: '30天后',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一年后',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 365)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      selectLoading: false,
      dialogVisible: false,
      levels: [],
      total: 0,
      rows: [],
      balanceForm: {
        studioId: this.id,
        isPlus: null,
        amount: null,
        remark: null,
        confirmPassword: null
      },
      balanceFormRules: {
        isPlus: [
          { required: true, message: '请选择操作类型', trigger: 'change' }
        ],
        amount: [{ required: true, message: '请填写金额', trigger: 'blur' }],
        confirmPassword: [{ required: true, message: '请填写确认密码', trigger: 'blur' }]
      },
      studioForm: {
        formData: {
          id: null,
          name: null,
          levelId: null
        },
        loading: false,
        rules: {
          enable: { required: true, message: '请选择状态', trigger: 'change' },
          account: [
            {
              required: true,
              message: '请输入账号'
            },
            {
              min: 5,
              max: 20,
              message: '账号长度需在5到20个字符之间'
            },
            {
              validator: (rule, value, callback) => {
                if (this.id) {
                  return callback()
                }
                studioUserApi.checkAccount(value).then((res) => {
                  if (res.data) {
                    return callback(new Error('账号已存在，请重新输入'))
                  }
                  return callback()
                })
              },
              trigger: 'blur'
            }
          ],
          name: [{ required: true, message: '请输入影楼名称', trigger: 'blur' }],
          tel: [{ required: true, message: '请输入影楼电话', trigger: 'blur' }]
        }
      }
    }
  },
  async created () {
    if (this.isEditMode) {
      this.getInfo()
    }
    this.getFactory()
  },
  computed: {
    ...mapGetters(['token']),
    isEditMode () {
      return this.id && this.id > 0
    }
  },
  methods: {
    async getInfo () {
      await this.getLevelSelect()
      const res = await studioAPI.getById(this.id)
      this.studioForm.formData = JSON.parse(JSON.stringify(res.data))
      this.getLogList()
    },
    /**
     * 搜索条件变更处理
     */
    handleFilter () {
      this.$refs.table.changeCondition()
    },
    /**
     * 分页信息变动事件处理
     * @param  {Object} pageInfo 分页信息
     */
    handlePageInfoChange (pageInfo) {
      this.getLogList(pageInfo)
    },
    getLogList (pageInfo) {
      if (
        Array.isArray(this.listQuery.dateArray) &&
        this.listQuery.dateArray.length === 2
      ) {
        this.listQuery.startTime = this.listQuery.dateArray[0] + ' 00:00:00'
        this.listQuery.endTime = this.listQuery.dateArray[1] + ' 23:59:59'
      } else {
        this.listQuery.startTime = null
        this.listQuery.endTime = null
      }
      amountChangeLogAPI
        .getPaged({ condition: this.listQuery, pageInfo })
        .then((response) => {
          console.log('res', response)

          this.rows = response.data.content
          this.total = response.data.totalElements
        })
    },
    onReCharge () {
      this.formLoading = true
      this.$refs.balanceForm.validate((valid) => {
        if (!valid) {
          this.formLoading = false
          return false
        }

        studioAPI
          .recharge(this.balanceForm)
          .then((res) => {
            this.$message.success('充值成功')
            this.$refs.balanceForm.resetFields()
            this.getInfo()
          })
          .finally(() => {
            this.formLoading = false
          })
      })
    },
    /**
     * 获取工厂数据
     */
    getFactory () {
      factoryApi.getFactory().then(response => {
        this.factory = response.data
      })
    },
    /**
     * 查询影楼下拉框信息
     */
    getLevelSelect (keyword) {
      if (this.studioForm.formData.level) {
        return
      }
      this.selectLoading = true
      levelAPI
        .getAll({ showLoading: false })
        .then((res) => {
          this.levels = res.data
          this.selectLoading = false
        })
        .catch((e) => {
          this.selectLoading = false
        })
    },
    handleSpec () {
      this.addLoad = true
      this.$refs.photoSpecsForm.validate((valid) => {
        if (valid) {
          this.studioForm.formData.photoSpecs.push(
            Object.assign({}, this.photoSpecsFormData)
          )
          this.dialogVisible = false
        }
        this.addLoad = false
      })
    },
    photoSpecsReset () {
      this.$nextTick(() => {
        this.$refs.photoSpecsForm.resetFields()
      })
    },
    gotoList () {
      this.$router.pushTo(this.$router.routesConfig.studioList)
    },
    onSubmit () {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false
        }
        this.studioForm.loading = true
        if (this.id) {
          studioAPI
            .update(this.studioForm.formData)
            .then(() => {
              this.studioForm.loading = false
              this.gotoList()
            })
            .catch(() => (this.studioForm.loading = false))
        } else {
          studioAPI
            .insert(this.studioForm.formData)
            .then(() => {
              this.studioForm.loading = false
              this.$message.success('添加影楼成功')
              this.gotoList()
            })
            .catch(() => (this.studioForm.loading = false))
        }
      })
    }
  }
}
</script>
